package algotithm.leetcode.string.test1297;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/15-22:28
 * @URL https://leetcode-cn.com/problems/maximum-number-of-occurrences-of-a-substring/
 * @Title 1297. 子串的最大出现次数
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        String s = "aababcaab";
        int maxLetters = 2;
        int minSize = 3;
        int maxSize = 4;
        int maxFreq = solution.maxFreq(s, maxLetters, minSize, maxSize);
        System.out.println(maxFreq);
    }

    public boolean isMatch(String s, int maxLetters) {
        char[] ch = s.toCharArray();
        HashSet<Character> set = new HashSet<>();
        for (int i = 0; i < ch.length; i++) {
            set.add(ch[i]);
            if (set.size() > maxLetters) {
                return false;
            }

        }
        return set.size() <= maxLetters;
    }

    public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {
        int res = 0;
        HashMap<String,Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (i + minSize > s.length()) {
                break;
            }
            String sub = s.substring(i,i + minSize);
            if (isMatch(sub,maxLetters)) {
                map.put(sub,map.getOrDefault(sub,0) + 1);
            }

        }

        for (String str : map.keySet()) {
            int num = map.get(str);
            res = Math.max(res,num);
        }
        return res;
    }
}
